import time
import cv2
import numpy as np

original_image = cv2.imread("pic/1.png")
h, w, t=original_image.shape
print(h,w)

image = original_image.copy()
cv2.namedWindow('image', 0)
cv2.resizeWindow('image', w, h)
cv2.imshow("image", image)


# 高斯滤波
image = cv2.GaussianBlur(image, (9,9),1,1)
# 转为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#转换为二值图像
# ret, binary = cv2.threshold(gray, 239, 255, cv2.THRESH_BINARY)

cv2.namedWindow('gray',0)
cv2.resizeWindow('gray',w,h)
cv2.imshow("gray", gray)

#再次检测边缘
edges = cv2.Canny(gray, 1, 100, 3)
# edges = cv2.Laplacian(gray, cv2.CV_8U)
cv2.namedWindow('edges',0)
cv2.resizeWindow('edges',w,h)
cv2.imshow("edges", edges)
cv2.imwrite('pic/edges_screen.png', edges)

# x=int(w/2)
# y=int(h/3)
#
# he=[]
# we=[]
# for i in range(h):
#     if edges[i][x]==255:
#         try:
#             if edges[i-1][x]==0 and edges[i+1][x]==0:
#                 for long in range(-8,8):
#                     if edges[i][x+long]!=255:
#                         break
#                     if long == 7:
#                         he.append(i)
#         except IndexError:
#             continue
# print(he)
# for i in range(w):
#     if edges[y][i]==255:
#         try:
#             if edges[y][i-1] == 0 and edges[y][i+1] == 0:
#                 for long in range(-8,8):
#                     if edges[y+long][i]!=255:
#                         break
#                     if long==7:
#                         we.append(i)
#         except IndexError:
#             continue
# print(we)
# cv2.rectangle(original_image, (we[0], he[0]), (we[-1],he[-1]), (36, 255, 12), 2)

lines = cv2.HoughLinesP(edges, 5, np.pi/2, 300, minLineLength=500, maxLineGap=10)
for line in lines:
    x1,y1,x2,y2 = line[0]
    cv2.line(original_image, (x1, y1), (x2,y2), (0,255,0),2)
cv2.namedWindow('detected',0)
cv2.resizeWindow('detected',w,h)
cv2.imshow("detected", original_image)
#cv2.imwrite('pic/detected9.png', original_image)
cv2.waitKey(0)



